<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>账号管理</el-breadcrumb-item>
    </el-breadcrumb>

    <Container class="u-mb15">
      <!-- 筛选 -->
      <el-form
        inline
        class="m-form--filter"
      >
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择客户名称"
            v-model="filter.customerId"
            @change="handleChangeCustomerOptions"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择产品"
            v-model="filter.productId"
            @change="handleChangeProductOptions"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择平台"
            v-model="filter.platformId"
            @change="handleChangePlatformOptions"
          >
            <el-option
              v-for="item in platformOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w200"
            size="mini"
            filterable
            multiple
            collapse-tags
            placeholder="请选择账号ID"
            v-model="filter.usernameId"
          >
            <el-option
              v-for="(item, index) in usernameOptions"
              :key="index"
              :label="`${item.name}${item.accountName ? `(${item.accountName}`: ''}${item.id ? `,${item.id})` : ''}`"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择运营方式"
            v-model="filter.operator"
          >
            <el-option
              v-for="item in [{value: null, label: '全部运营方式'}].concat(OPERATOR_OPTION)"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            @click="search"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </Container>

    <Container>
      <!-- 表格操作 -->
      <el-form
        inline
        class="m-table--handle"
      >
        <el-form-item>
          <el-button
            size="mini"
            type="primary"
            @click="$router.push({
              name: 'flow-account-detail',
              query: {
                action: 'create'
              }
            })"
          >新增</el-button>
          <el-button
            size="mini"
            @click="multiChangeState(2)"
          >启用</el-button>
          <el-button
            size="mini"
            @click="multiChangeState(1)"
          >停用</el-button>
        </el-form-item>
         <el-form-item>
            <ImportTable :importName="importName" :importUrl="importUrl"></ImportTable>
        </el-form-item>
        <el-form-item>
          <el-button
              @click="exportExcel('/manage/api/bus/account/export',requestSearch)"
              size="mini"
            >导出</el-button>
        </el-form-item>
        <el-form-item>
          <el-link type="primary" :underline="false" @click="downloadTemplate">下载导入模版</el-link> 
        </el-form-item>
        <CustomTableColumn :columns.sync="tableColumn" />
      </el-form>
      <!-- 表格 -->
      <el-table
        border
        stripe
        :data="tableData"
        @selection-change="changeTableSelection"
      >
        <el-table-column
          type="selection"
          width="35"
          fixed
          :selectable="handleSelectable"
        >
        </el-table-column>
        <el-table-column
          align="center"
          v-for="(item, index) in filterTableColumn"
          :label="item.label"
          :key="index"
        >
          <template slot-scope="scope">
            <!-- 客户角色 -->
            <template v-if="item.prop === 'customerRole'">{{mapOptionLabel(CUSTOMER_ROLE_OPTION, scope.row.customerRole)}}</template>
            <!-- 运营方式 -->
            <template v-else-if="item.prop === 'operator'">{{mapOptionLabel(OPERATOR_OPTION, scope.row.operator)}}</template>
            <!-- 当前返点 -->
            <template v-else-if="item.prop === 'rebates'">{{scope.row.rebates + '%'}}</template>
            <!-- 账号名称 -->
            <template v-else-if="item.prop === 'accountName'">{{scope.row.accountName == '' || scope.row.accountName == null ? '-' : scope.row.accountName}}</template>
            <!-- 是否启用 -->
            <template v-else-if="item.prop === 'status'">
              <el-switch
                :width="34"
                :value="scope.row.status"
                :active-value="2"
                :inactive-value="1"
                @change="changeStatus(scope.row.id, scope.row.status === 1 ? 2 : 1)"
              ></el-switch>
            </template>
            <!-- 其他 -->
            <template v-else>{{scope.row[item.prop]}}</template>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="$router.push({
                name: 'flow-account-detail',
                query: {
                  action: 'edit',
                  id: scope.row.id
                }
              })"
            >编辑</el-button>
            <el-button
              type="text"
              @click="$router.push({
                name: 'flow-account-detail',
                query: {
                  action: 'detail',
                  id: scope.row.id
                }
              })"
            >查看</el-button>
            <!-- <el-button
              type="text"
              @click="removeAccount(scope.row.id)"
            >删除</el-button> -->
            <el-button
              type="text"
              @click="opendialogOperate({rebates: scope.row.rebates, accountId:scope.row.id, operator:scope.row.operator, operate:scope.row.operatorBy, productId: scope.row.productId})"
            >设置运营方式</el-button>
             <el-button
               type="text"
                size="mini"
                v-if="scope.row.status == 1"
                @click="handleDelete(scope.row.id)"
              >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        :page-sizes="[50, 100, 500, 1000]"
        :page-size="page.pageSize"
        layout="total, prev, pager, next, sizes"
        :total="pageTotal"
        @size-change="handlePagerSizeChange"
        @current-change="handlePagerCurrentChange"
      />
    </Container>

    <!-- 运营方式 -->
    <el-dialog
      title="运营方式"
      :visible.sync="dialogOperateVisible"
      width="542px"
    >
      <el-alert
        type="warning"
        :closable="false"
        class="u-mb20"
      >
        1.已导入数据的账号，不可更改运营方式！<br>
        2.已生成结算单的数据，运营人员如有变更，不会同步更改！
      </el-alert>
      <el-form
        label-width="100px"
        :model="dialogOperateData"
        :rules="dialogOperateRules"
        ref="dialogOperateForm"
      >
        <el-form-item
          label="运营方式"
          required
          prop="operator"
        >
          <el-select
            size="small"
            class="u-w270"
            v-model="dialogOperateData.operator"
            @change="handlOperateChange"
          >
            <el-option
              v-for="item in OPERATOR_OPTION"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="返点">{{dialogOperateData.rebates + '%'}}<Tip inline>（如没有设置返点,请至产品管理模块添加）</Tip>
        </el-form-item>
        <el-form-item
          v-show="false"
          label="运营人员"
          v-if="dialogOperateData.operator === 1"
        >
          <el-row v-if="!dialogOperateData.operate.length">
            <el-button
              size="small"
              type="primary"
              @click="addOperate"
            >添加</el-button>
          </el-row>
          <el-row
            v-for="(item, index) in dialogOperateData.operate"
            :key="index"
          >
            <el-form-item
              class="u-dib"
              :prop="'operate.' + index + '.startDate'"
              :rules="{
                required: true,
                message: '请选择日期',
                trigger: ['blur', 'change']
              }"
            >

              <el-date-picker
                class="u-w140"
                type="date"
                placeholder="选择日期"
                size="small"
                v-model="item.startDate"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="dialogOperatePickerOptions"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              
              class="u-dib u-ml10"
              :prop="'operate.' + index + '.operatorBy'"
              :rules="{
                required: true,
                message: '请输入运营人',
                trigger: ['blur', 'change']
              }"
            >
              <el-input
                class="u-w120"
                size="small"
                placeholder="请输入运营人"
                v-model.trim="item.operatorBy"
              ></el-input>
              <el-button
                size="small"
                type="primary"
                class="u-ml10"
                @click="addOperate"
              >添加</el-button>
              <el-button
                size="small"
                class="u-ml10"
                @click="removeOperate(index)"
              >删除</el-button>
            </el-form-item>
          </el-row>
        </el-form-item>
      </el-form>

      <el-row
        type="flex"
        justify="end"
      >
        <el-button
          size="small"
          @click="dialogOperateVisible = false"
        >取消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="handleDialogOperateSure"
        >确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
import moment from "moment";

import Container from "@/components/container";
import CustomTableColumn from "@/components/custom-table-column";
import Tip from "@/components/tip";
import ImportTable from "@/components/import-table.vue";

import { exportExcel } from '@/utils/fileDown.js';
import { OPERATOR_OPTION, CUSTOMER_ROLE_OPTION } from "@/assets/js/flow-option";
import { mapOptionLabel } from "@/util";

export default {
  name: "flow-account",
  components: {
    Container,
    CustomTableColumn,
    Tip,
    ImportTable
  },
  data() {
    return {
      OPERATOR_OPTION,
      CUSTOMER_ROLE_OPTION,

      // 下拉
      customerOptions: [],
      productOptions: [],
      platformOptions: [],
      usernameOptions: [],

      // 筛选
      filter: {
        customerId: Number(this.$route.query.customerId) || null,
        productId: Number(this.$route.query.productId) || null,
        platformId: Number(this.$route.query.platformId) || null,
        usernameId: [null],
        operator: null
      },

      // 导入
      importName:'导入',
      importUrl:'/manage/api/bus/account/import_account',

      // 运营方式
      dialogOperateVisible: false,
      dialogOperateData: {
        operate: []
      },
      dialogOperateRules: {
        operator: {
          required: true,
          message: "请选择运营方式",
          trigger: ["blur", "change"]
        }
      },

      tableData: [],
      tableSelectionData: [],
      tableColumn: [
        {
          label: "平台名称",
          prop: "platformName",
          visible: true
        },
        {
          label: "登录账号",
          prop: "username",
          visible: true
        },
        {
          label: "账号名称",
          prop: "accountName",
          visible: true
        },
        {
          label: "账号ID",
          prop: "usernameId",
          visible: true
        },
        {
          label: "客户名称",
          prop: "customerName",
          visible: true
        },
        {
          label: "客户角色",
          prop: "customerRole",
          visible: true
        },
        {
          label: "产品名称",
          prop: "productName",
          visible: true
        },
        {
          label: "运营方式",
          prop: "operator",
          visible: true
        },
        {
          label: "当前返点",
          prop: "rebates",
          visible: true
        },
        // {
        //   label: "当前运营人员",
        //   prop: "operatorBy",
        //   visible: true
        // },
        {
          label: "是否启用",
          prop: "status",
          visible: true
        }
      ],
      page: {
        pageNo: 1,
        pageSize: 50
      },
      pageTotal: 0
    };
  },
  computed: {
    requestSearch() {
      return {
         ...this.filter,
          ...this.page,
          usernameId: this.filter.usernameId.includes(null)
            ? null
            : this.filter.usernameId.join()
      }
    },
    filterTableColumn() {
      return this.tableColumn.filter(item => item.visible);
    },
    // 运营人日期不可重复
    dialogOperatePickerOptions() {
      let vm = this;
      return {
        disabledDate(date) {
          return vm.dialogOperateData.operate.some(item => {
            return item.startDate === moment(date).format("YYYY-MM-DD");
          });
        }
      };
    }
  },
  methods: {
    mapOptionLabel,
    exportExcel,
     // 下载模板
    downloadTemplate() {
      location.href = "https://s.55duanzi.com/CMS/账号管理导入表格.xls";
    },
    // 下拉
    fetchCustomerOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_name",
        params: {
          status: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerOptions = [
            {
              id: null,
              name: "全部客户"
            }
          ].concat(res.data.data);
          if (this.$route.query.customerId) {
            this.filter.customerId = Number(this.$route.query.customerId);
          }
        }
      });
    },
    fetchProductOptions(customerId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/product/get_all_product",
        params: { customerId: Number(customerId) }
      }).then(res => {
        if (res.data.code === 0) {
          this.productOptions = [
            {
              id: null,
              name: "全部产品"
            }
          ].concat(res.data.data);
          if (this.$route.query.productId) {
            this.filter.productId = Number(this.$route.query.productId);
          }
        }
      });
    },
    fetchPlatformOptions(customerId = 0, productId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/platform/get_platform",
        params: {
          status: 0,
          customerId: Number(customerId),
          productId: Number(productId)
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.platformOptions = [
            {
              id: null,
              name: "全部平台"
            }
          ].concat(res.data.data);
          if (this.$route.query.platformId) {
            this.filter.platformId = Number(this.$route.query.platformId);
          }
        }
      });
    },
    fetchUsernameOptions(customerId = 0, productId = 0, platformId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/account/get_username_id_list",
        params: {
          customerId: Number(customerId),
          productId: Number(productId),
          platformId: Number(platformId)
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.usernameOptions = [
            {
              id: null,
              name: "全部账号ID"
            }
          ].concat(res.data.data);
        }
      });
    },
    handleChangeCustomerOptions() {
      this.filter.productId = null;
      this.filter.platformId = null;
      this.filter.usernameId = [null];
      this.fetchProductOptions(this.filter.customerId);
    },
    handleChangeProductOptions() {
      this.filter.platformId = null;
      this.filter.usernameId = [null];
      this.fetchPlatformOptions(this.filter.customerId, this.filter.productId);
    },
    handleChangePlatformOptions() {
      this.filter.usernameId = [null];
      this.fetchUsernameOptions(this.filter.customerId, this.filter.productId, this.filter.platformId);
    },

    // 运营方式
    opendialogOperate(data) {
      this.dialogOperateData = cloneDeep(data);
      this.dialogOperateVisible = true;
    },
    handlOperateChange(e){
      this.dialogOperateData.operate = []
      this.$http({
        method: "post",
        url: "/manage/api/bus/product/get_rebate",
        params: {
          operator: e,
          productId: this.dialogOperateData.productId
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.dialogOperateData.rebates = res.data.data
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    addOperate() {
      this.dialogOperateData.operate.push({ operatorBy: "", startDate: "" });
    },
    removeOperate(index) {
      this.dialogOperateData.operate.splice(index, 1);
    },
    handleDialogOperateSure() {
      this.$refs.dialogOperateForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/account/operator",
            data: this.dialogOperateData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("操作成功！");
              this.dialogOperateVisible = false;
              this.getTable();
            }else{
              this.$message.error(res.data.msg);
              this.dialogOperateVisible = false;
            }
          });
        }
      });
    },
    // 运营人员
    getCurrentOperate(data = []) {
      let len = data.length;
      if (len) {
        let item = data[len - 1];
        return `${item.operatorBy}`;
      }
      return "-";
    },

    // 列表
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    getTable() {
      this.$http({
        method: "post",
        url: "/manage/api/bus/account/get_list",
        data: {
          ...this.filter,
          ...this.page,
          usernameId: this.filter.usernameId.includes(null)
            ? null
            : this.filter.usernameId.join()
        }
      }).then(res => {
        if (res.data.code === 0) {
          let data = res.data.data;
          this.tableData = data.list;
          this.pageTotal = data.listCount;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    multiChangeState(action) {
      if (!this.tableSelectionData.length) {
        return this.$message.warning("请选择需要操作的选项！");
      }
      this.changeStatus(
        this.tableSelectionData.map(item => item.id).join(),
        action
      );
    },
    changeStatus(id, status) {
      this.$http({
        method: "post",
        url: "/manage/api/bus/account/status",
        params: {
          ids: id,
          status
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.$message.success(`${status === 1 ? "停用" : "启用"}成功！`);
          this.getTable();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    handleDelete(id) {
      this.$confirm("是否删除此账号？删除后不可恢复！", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
           this.$http({
            method: "post",
            url: "/manage/api/bus/account/del",
            params: {
              ids: id
            }
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("删除成功!");
              this.getTable();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {});
    },
    removeAccount() {
      this.$confirm("是否删除此账号？删除后不可恢复！", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {})
        .catch(() => {});
    },
    handleSelectable() {
      return true;
    },
    changeTableSelection(data) {
      this.tableSelectionData = data;
    },
    handlePagerSizeChange(v) {
      this.page.pageSize = v;
      this.getTable();
    },
    handlePagerCurrentChange(v) {
      this.page.pageNo = v;
      this.getTable();
    }
  },
  activated(){
    // 筛选
    if(this.$route.query.customerId){
      this.filter = {
        customerId: Number(this.$route.query.customerId) || null,
        productId: Number(this.$route.query.productId) || null,
        platformId: Number(this.$route.query.platformId) || null,
        usernameId: [null],
        operator: null
      }
    }
    this.getTable();
  },
  created() {
    this.fetchCustomerOptions();
    this.fetchProductOptions();
    this.fetchPlatformOptions();
    this.fetchUsernameOptions();
  }
};
</script>